﻿using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace block_explorer.NoiseSystem
{
    public class NoiseRenderer
    {
        // debugging stuff
        private IList<Nodes.INode> mDebugNodes;
        private IList<Texture2D> mDebugTextures;
        private Vector2 mTextureSize;
        private SpriteBatch mSpriteBatch;

        public NoiseRenderer()
        {
            mDebugNodes = new List<Nodes.INode>();
        }

        public void AddNoise(Nodes.INode node)
        {
            mDebugNodes.Add(node);
        }

        public void DebugDraw(GraphicsDevice device, Vector2 textureSize, Vector2 screenPos)
        {
            if (mSpriteBatch == null)
            {
                mSpriteBatch = new SpriteBatch(device);
            }

            if (mTextureSize != textureSize)
            {
                mTextureSize = textureSize;
                RegenerateDebugTextures(device);
            }

            mSpriteBatch.Begin();

            foreach (var texture in mDebugTextures)
            {
                mSpriteBatch.Draw(texture, new Rectangle((int)screenPos.X, (int)screenPos.Y, (int)textureSize.X, (int)textureSize.Y), Color.White);
                screenPos.Y += textureSize.Y + 2;
            }

            mSpriteBatch.End();
        }

        private void RegenerateDebugTextures(GraphicsDevice device)
        {
            int sizeX = (int)mTextureSize.X;
            int sizeY = (int)mTextureSize.Y;

            mDebugTextures = new List<Texture2D>();
            foreach (var node in mDebugNodes)
            {
                Texture2D texture = new Texture2D(device, sizeX, sizeY);
                Color[] colorBuffer = new Color[sizeX * sizeY];
                texture.GetData(colorBuffer);
                for (int y = 0; y < sizeY; ++y)
                {
                    for (int x = 0; x < sizeX; ++x)
                    {
                        float v = (float)node.Value(x, sizeY - y, 5.0);
                        colorBuffer[x + (y * sizeX)] = new Color(v, v, v);
                    }
                }
                texture.SetData(colorBuffer);
                mDebugTextures.Add(texture);
            }
        }
    }
}
